package com.kehutong.wwin.service.service;

import com.kehutong.common.errcode.Result;
import com.kehutong.common.util.Token;
import com.kehutong.wwin.service.entity.Corp;
import com.kehutong.wwin.service.entity.Suite;
import com.kehutong.wwin.service.util.URLConstant;
import com.kehutong.wwin.service.util.WwInHttpClient;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.jdbc.JdbcSession;

@WebService("/wwin-service/template/wwin")
public class ToWwinTemplateMessageService {

    @Inject
    private WwInHttpClient wwInHttpClient;

    @Inject
    private CorpService corpService;

    @Inject
    private JdbcSession jdbcSession;

    @Inject
    private URLConstant urlConstant;

    @ReqMapping("/message/send")
    public Object sendTemplateMessage(Token token, JSONObject jsonObject) throws Exception {
        Corp corp = corpService.getCropByKhtId(token.getCompanyNo());
        Suite suite = jdbcSession.findOne(Suite.class)
                .eq("corpId", corp.getId())
                .eq("deleted", false).exe();
        String accessToken = corpService.geAppAccessToken(suite);
        String url = getURL(corp.getKhtid(), urlConstant.getWorkRepireUrl(jsonObject.getString("id")));
        sendAppCard(accessToken, jsonObject, url);
        return Result.success();
    }

    private void sendAppCard(String accessToken, JSONObject json, String url) throws Exception {
        wwInHttpClient.post("/cgi-bin/message/send", http -> {
            http.addParam("access_token", accessToken);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("touser", json.getString("userIds"));
            jsonObject.put("msgtype", "textcard");
            jsonObject.put("agentid", " ");

            JSONObject cardText = new JSONObject();
            cardText.put("title", json.getString("title"));
            cardText.put("description", json.getString("content"));
            cardText.put("url", url);
            cardText.put("btntxt", "详情");

            jsonObject.put("textcard", cardText);
            http.setBody(jsonObject.toJSONString());
        });
    }

    private String getURL(String corp, String url) {
        StringBuilder buf = new StringBuilder(url);

        if (url.contains("?")) {
            buf.append("&state=1_").append(corp);
        } else {
            buf.append("?state=1_").append(corp);
        }

        return buf.toString();
    }
}
